import PlusOutlined from "@ant-design/icons/PlusOutlined"
import { BankCard, BankCardFunding, BankCardService, HolderType } from "@mallfoundry/finance"
import { Button, Card, Col, Divider, Popconfirm, Row, Space } from "antd"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useParams } from "react-router-dom"
import Page from "../../components/page"
import { useBankCards } from "../../hooks/finance"
import { useLoading } from "../../hooks/loading"
import { useStore } from "../../hooks/store"
import { BankCardBindModal } from "./bank-card-bind"
import { BankCardEditModal } from "./bank-card-edit"
import classes from "./bank-card-list.module.scss"

interface BankCardListItemProps {
  added?: boolean
  card?: BankCard
  onAdd?: () => void
  onEdit?: (card: BankCard) => void
  onUnbind?: () => void
}

function BankCardListItem(props: BankCardListItemProps) {
  const { card, added, onAdd, onEdit, onUnbind } = props
  const [deleting, setDeleting] = useState(false)

  function handleClick() {
    if (added && _.isFunction(onAdd)) {
      onAdd()
    }
  }

  function handleEdit() {
    if (!_.isUndefined(card) && _.isFunction(onEdit)) {
      onEdit(card)
    }
  }

  function handleUnbind() {
    const id = card?.id
    if (_.isUndefined(id)) {
      return
    }
    setDeleting(true)
    BankCardService
      .unbindBankCard(id)
      .then(onUnbind)
      .finally(() => setDeleting(false))

  }

  function renderHolderType() {
    if (card?.holderType === HolderType.Individual) {
      return "对私"
    } else if (card?.holderType === HolderType.Company) {
      return "对公"
    }
    return "未知"
  }

  function renderFunding() {
    if (card?.funding === BankCardFunding.Debit) {
      return "储蓄卡"
    } else if (card?.funding === BankCardFunding.Credit) {
      return "信用卡"
    }
    return "未知"
  }

  return (
    <div className={classNames(classes.BankCardListItem, {
      [classes.BankCardListAddItem]: added,
    })} onClick={handleClick}>
      {
        added &&
        <Space direction="vertical">
          <PlusOutlined/>
          添加银行卡
        </Space>
      }
      {
        !(added || _.isUndefined(card)) &&
        <>
          <div className={classes.BankCardInfo}>
            <Row justify="space-between" align="middle">
              <Col style={{ fontSize: "14px" }}>{card.bankName}</Col>
              <Col>{renderHolderType()}</Col>
            </Row>
            <div className={classes.BankCardFunding}>{renderFunding()}</div>
            <div className={classes.BankCardNumber}>{card.number}</div>
          </div>
          <div className={classes.BankCardItemFooter}>
            <Space>
              <Button type="link" size="small" onClick={handleEdit}>修改</Button>
              <Divider type="vertical"/>
              <Popconfirm placement="bottom" title="您确定要删除吗？"
                          okButtonProps={{ loading: deleting }}
                          onConfirm={handleUnbind}>
                <Button type="link" size="small">删除</Button>
              </Popconfirm>
            </Space>
          </div>
        </>
      }
    </div>
  )
}

export default function BankCardList() {
  const { storeId } = useParams<{ storeId: string }>()
  const { loading: storeLoading, store: { accountId = "" } } = useStore(storeId)
  const [cardBindModalVisible, setCardBindModalVisible] = useState(false)
  const [cardEditModalVisible, setCardEditModalVisible] = useState(false)
  const [editCard, setEditCart] = useState(undefined as undefined | BankCard)
  const {
    loading: cardsLoading,
    elements: cards,
    refresh: refreshCards,
  } = useBankCards({ accountId })

  const [loading] = useLoading([storeLoading, cardsLoading])

  function handleEdit(aCard: BankCard) {
    setEditCart(aCard)
    setCardEditModalVisible(true)
  }

  return (
    <div className={classes.BankCardList}>
      <BankCardBindModal accountId={accountId} visible={cardBindModalVisible}
                         onOk={() => {
                           setCardBindModalVisible(false)
                           refreshCards()
                         }}
                         onCancel={() => setCardBindModalVisible(false)}/>
      <BankCardEditModal visible={cardEditModalVisible} card={editCard}
                         onCancel={() => setCardEditModalVisible(false)}
                         onOk={() => {
                           setCardEditModalVisible(false)
                           refreshCards()
                         }}/>
      <Page.Header title="银行卡管理" ghost={false}/>
      <Page.Content loading={loading}>
        <Card className={classes.PageCard}>
          <div className={classes.BankCardListContent}>
            {_.map(cards, card => <BankCardListItem key={card.id} card={card}
                                                    onEdit={handleEdit}
                                                    onUnbind={refreshCards}/>)}
            <BankCardListItem added onAdd={() => setCardBindModalVisible(true)}/>
          </div>
        </Card>
      </Page.Content>
    </div>
  )
}
